# -*- coding: utf-8 -*-

"""
处理kg json文件的工具类
"""

from __future__ import unicode_literals
from __future__ import absolute_import

import json
from decimal import Decimal
from datetime import datetime, date

from six import text_type


# 将float转换为string，以保持数据精度
class FakeFloat(float):
    def __init__(self, value):
        super(FakeFloat, self).__init__()
        self._value = value

    def __repr__(self):
        return text_type(self._value)


def default_encode(o):
    if isinstance(o, Decimal):
        return FakeFloat(o)
    elif isinstance(o, datetime):  # since datetime is a subclass of date, it is important to first test datetime
        return o.strftime("%Y-%m-%d %H-%M-%S")
    elif isinstance(o, date):
        return o.strftime("%Y-%m-%d")
    raise TypeError(repr(o) + " is not JSON serializable")


def entity_json_encode(entity):
    return json.dumps(entity, ensure_ascii=False, default=default_encode)


def entity_json_decode(text):
    return json.loads(text, parse_float=Decimal)


def list_item_to_string(dt):
    if dt is None:
        return ""
    elif isinstance(dt, text_type):
        return dt
    if isinstance(dt, list) or isinstance(dt, dict):
        return entity_json_encode(dt)
    else:
        return text_type(dt)


def item_to_string(dt, separator=';'):
    if dt is None or isinstance(dt, text_type):
        return dt
    elif isinstance(dt, list):
        return separator.join(list_item_to_string(item) for item in dt)
    elif isinstance(dt, dict):
        return entity_json_encode(dt)
    else:
        return text_type(dt)
